<?php

namespace App\Http\Controllers;

use App\Common\Sql;
use App\Exceptions\ApiException;
use App\Logic\ActivityLogic;
use Illuminate\Support\Facades\DB;

class ReadMail extends Base
{

    /**
     * 阅读邮件
     * @return string
     */
    public function logic()
    {
        DB::table('t_mail_info')->where('id', $this->param["mail_id"])->where('uid', $this->uid)->update(['is_read' => 1]);
        return $this->returnData();
    }


    /**
     * 阅读附件邮件
     * @return string
     * @throws ApiException
     */
    public function readAccessoryMail()
    {
        $object = DB::table('t_mail_info')->where('id', $this->param['mail_id'])->where('type', 2)->first(['rule', 'status', 'uid','is_read','is_get']);
        if (empty($object)) {
            throw new ApiException('附件邮件不存在');
        }
        if ($object->is_get == 1) {
            throw new ApiException('已经领取过了');
        }
//        $data = ActivityLogic::instance()->analysisHandle($object->rule, $object->uid, '内测有礼');

        //把附件 加入到背包道具
        $rule_arr = explode('|',$object->rule);
        $response = [];
        foreach ($rule_arr as $value) {
            $value_arr = explode(':',$value);
            DB::select("INSERT INTO `t_user_bag_info` (`item_id`,`uid`,`num`) VALUES ($value_arr[0],$object->uid,$value_arr[1]) ON DUPLICATE KEY UPDATE `num` = `num` + $value_arr[1]");
        }
        DB::table('t_mail_info')->where('id', $this->param['mail_id'])->where('type', 2)->update(['is_get' => 1]);
        return $this->returnData($response);
    }


    /**
     * 删除邮件
     * @return string
     * @throws ApiException
     */
    public function delete()
    {
        $object = DB::table('t_mail_info')->where('id',$this->param['mail_id'])->where('uid',$this->uid)->first(['type','is_read','is_get']);
        if (empty($object)) {
            throw new ApiException('邮件不存在');
        }
        if ($object->type == 2 && $object->is_get == 0) {
            throw new ApiException('附件未领取,不能删除');
        }
        DB::table('t_mail_info')->where('id',$this->param['mail_id'])->update(['status' => 0]);
        return $this->returnData();
    }


}

